import React, { PureComponent } from 'react';
import { Tabs, Row, Typography, Col, Button, Select, Form, TreeSelect, message, Modal } from 'antd';
import qs from 'qs';
import { connect } from 'dva';
import router from 'umi/router';
import _ from 'lodash';
import moment from 'moment';
import * as apis from '@/services/ValueApprovelMgr';
import * as api from '@/services/ContractPlanMgr';
import Btns from '@/components/Btns';
import { showConfirm } from '@/utils/utils';
import TextScroll from './TextScroll';
import styles from './index.less';
import { handlerApprovalStatusColor } from '@/utils/publicFunction';
import { setSignPlanVersionName, setSignPlanAccessVersionName } from '@/utils/versions_name';
import AuthorizedButton from '@/components/AuthorizedButton';
import MyBasicInfo from '@/components/MyBasicInfo';

const { Text } = Typography;
const { TabPane } = Tabs;
const { Option } = Select;

@connect(state => ({
  versions: state.ContractPlanVersions.data,
  overAllYears: state.ContractPlanItems.overAllYears,
  currentYear: state.ContractPlanItems.currentYear,
  currentMonths: state.ContractPlanItems.currentMonths,
}))
@Form.create()
export default class PageTop extends PureComponent {
  state = {
    agentInfo: [],
    visible: false,
    toDoItem: [],
  };

  componentDidMount() {
    this.handlerAgentInfo(this.props.match.params);
  }

  componentWillReceiveProps(nextPorps) {
    if (this.props.match.params !== nextPorps.match.params) {
      this.handlerAgentInfo(nextPorps.match.params);
    }
  }

  // 按钮
  buildBtnsList = props => {
    const { versions, versionState, match, currentState } = props;
    const BtnsList = [];
    if (versions && versions.length) {
      // 预算版不显示手动设置为预算版
      if (match.params.category !== 'budget') {
        BtnsList.push({
          authority: 'business_signing_setBudgetVertion',
          value: '设置为预算版',
          btnAttribute: {
            className: 'red-button',
            onClick: this.props.setBudgetVersion,
            loading: this.props.setBudgetVersionLoading,
          },
        });
      } else {
        BtnsList.push({
          authority: 'business_signing_copyBudgetVertion',
          value: '复制预算版',
          btnAttribute: {
            className: 'red-button',
            onClick: this.props.copyBudgetVersion,
            loading: this.props.setBudgetVersionLoading,
          },
        });
      }
      // 导出报表
      BtnsList.push({
        authority: 'business_signing_exportReport',
        value: '导出报表',
        btnAttribute: {
          className: 'yellow-button',
          onClick: this.overAllValueExport,
        },
      });
      // 查看审批
      if (
        versionState === 'examined_approved' ||
        versionState === 'approved' ||
        versionState === 'failure_approved' ||
        versionState === 'success_approved'
      ) {
        BtnsList.push({
          authority: 'business_signing_viewApproval',
          value: '查看审批',
          btnAttribute: {
            className: 'yellow-button',
            onClick: () => {
              const parameters = {
                versionId: match.params.version,
              };
              apis.goodsApprovedViewUsingGET({ params: parameters }).then(data => {
                if (data && data.code * 1 === 1) {
                  if (data.data.status * 1 === 1) {
                    window.open(`${data.data.url}`);
                  } else {
                    message.warning(data.data.message);
                  }
                }
              });
            },
          },
        });
      }
      if (versionState === 'not_prepared' || versionState === 'organization') {
        // 删除版本
        BtnsList.push({
          authority: 'business_signing_delete',
          value: '删除版本',
          btnAttribute: {
            onClick: () =>
              showConfirm(
                () => this.props.deletePriceVersion(),
                '确定要删除该版本吗？',
                '删除后，该版本将不可用。',
              ),
          },
        });
      }

      if (
        currentState &&
        currentState.length &&
        match.params.category === 'investment' &&
        currentState[0].isAssessmentVersion * 1 === 0
      ) {
        BtnsList.unshift({
          authority: 'business_signing_setVersionAssessment',
          value: '设为考核版',
          btnAttribute: {
            className: 'red-button',
            onClick: () => this.props.setVersionAssessment(match.params),
          },
        });
      }
    }
    return BtnsList;
  };

  changeCurrentMonths = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ContractPlanItems/changeCurrentMonths',
      payload: {
        currentMonths: value,
      },
    });
  };

  // 导出报表
  overAllValueExport = () => {
    const { match } = this.props;
    const params = {
      versionId: match.params.version,
    };
    const sessionToken = localStorage.getItem('sessionToken');
    const exportQueryString = qs.stringify({ ...params, sessionToken });
    window.open(
      `${process.env.apiUrl}/api/v1/signPlan/signPlanVersion/signPlanVersionExport?${exportQueryString}`,
    );
  };

  // 实时查询 签约门户待办信息
  handlerAgentInfo = obj => {
    const self = this;
    const params = {
      id: `${obj.stage}${obj.category}`,
    };
    api.getPortalTodoUsingGET({ params }).then(result => {
      const condition =
        result && result.code === 1 && result.data && Object.keys(result.data).length > 0;
      if (condition) {
        self.setState({
          agentInfo: [result.data],
        });
      } else {
        self.setState({
          agentInfo: [],
        });
      }
    });
  };

  getStayToThingId = item => {
    const { visible } = this.state;
    this.setState({
      visible: !visible,
      toDoItem: [item],
    });
  };

  /**
   * @Descripttion: 生成版本信息数据
   * @param {*} versionInfo 当前版本信息
   * @return {*} object
   */
  setBasicInfoData = versionInfo => {
    const basicInfo = [
      {
        label: '版本名称',
        span: 2,
        value: setSignPlanVersionName(versionInfo),
      },
      {
        label: '创建人',
        value: versionInfo.createUser,
      },
      {
        label: '创建时间',
        value: moment(versionInfo.createTime).format('YYYY-MM-DD HH:mm:ss'),
      },
      {
        label: '创建方式',
        value: versionInfo.createMethodName,
      },
      {
        label: '更新时间',
        value: moment(versionInfo.updateTime || versionInfo.createTime).format(
          'YYYY-MM-DD HH:mm:ss',
        ),
      },
    ];
    const accessInfo = [
      {
        label: ['budget'].includes(versionInfo.versionType) ? '签约版本' : '供货版本',
        value: setSignPlanAccessVersionName(versionInfo),
      },
    ];

    return {
      basicInfo,
      accessInfo,
    };
  };

  handleCancel = () => {
    const { visible } = this.state;
    this.setState({
      visible: !visible,
      toDoItem: [],
    });
  };

  changeCurrentYear(value) {
    const { dispatch } = this.props;
    const self = this;
    dispatch({
      type: 'ContractPlanItems/changeCurrentYear',
      payload: {
        currentYear: value,
      },
      callback: () => {
        self.props.getItems(self.props);
      },
    });
  }

  render() {
    const months = [
      {
        title: '年度合计',
        value: '14',
        key: '14',
      },
      {
        title: '全部月份',
        value: '13',
        key: '13',
        children: [
          { key: '1', value: '1', title: '1月' },
          { key: '2', value: '2', title: '2月' },
          { key: '3', value: '3', title: '3月' },
          { key: '4', value: '4', title: '4月' },
          { key: '5', value: '5', title: '5月' },
          { key: '6', value: '6', title: '6月' },
          { key: '7', value: '7', title: '7月' },
          { key: '8', value: '8', title: '8月' },
          { key: '9', value: '9', title: '9月' },
          { key: '10', value: '10', title: '10月' },
          { key: '11', value: '11', title: '11月' },
          { key: '12', value: '12', title: '12月' },
        ],
      },
    ];
    const { params } = this.props.match;
    const activeKey = params.category;
    const { versions, overAllYears, currentYear, currentMonths } = this.props;
    const { visible, agentInfo, toDoItem } = this.state;
    // console.log(currentMonths, 'currentMonths');
    let versionState = '';
    let currentState = [];
    if (versions.length > 0 && params.version) {
      currentState = _.filter(versions, { versionId: params.version });
      if (currentState.length) {
        versionState = currentState[0].versionStateCode;
      }
    }
    const BtnsList = this.buildBtnsList({ versionState, ...this.props, currentState });
    const attribute = {
      wrapClassName: styles.aletratinon,
      title: '版本变动消息提醒',
      width: '90%',
      height: '50%',
      visible,
      centered: true,
      onCancel: () => this.handleCancel(),
      footer: (
        <div>
          <Button
            type="primary"
            onClick={() => {
              this.setState({
                visible: false,
              });
              this.props.createPriceVersion();
            }}
            disabled={!visible}
          >
            创建版本
          </Button>
          <Button onClick={() => this.handleCancel()}>关闭</Button>
        </div>
      ),
    };
    return (
      <>
        {visible ? (
          <Modal {...attribute}>
            <span>{`[${toDoItem[0].todoType}]${toDoItem[0].content}`}</span>
          </Modal>
        ) : null}
        <Tabs
          activeKey={activeKey}
          animated={false}
          onChange={value => {
            router.push(
              `/OperatingPlan/ContractPlan/${params.level1}/${params.level2}/${params.project}/${params.stage}/${value}`,
            );
          }}
          size="large"
          tabBarExtraContent={
            <Row type="flex">
              {this.state.agentInfo.length > 0 ? (
                <Col>
                  <TextScroll
                    agentInfo={agentInfo}
                    getStayToThingId={v => this.getStayToThingId(v)}
                  />
                </Col>
              ) : null}
              <Col>
                {params.category !== 'budget' && (
                  <>
                    <AuthorizedButton authority="business_signing_abnormalCreate">
                      <Button
                        className="red-button"
                        onClick={this.props.createPriceAbnormalVersion}
                        loading={this.props.loading}
                      >
                        创建异常版本
                      </Button>
                    </AuthorizedButton>
                    <AuthorizedButton authority="business_signing_create">
                      <Button
                        type="primary"
                        onClick={this.props.createPriceVersion}
                        loading={this.props.loading}
                        style={{ marginLeft: 5 }}
                      >
                        创建版本
                      </Button>
                    </AuthorizedButton>
                  </>
                )}
              </Col>
            </Row>
          }
        >
          <TabPane tab="月度动态版" key="dynamic"></TabPane>
          <TabPane tab="预算版" key="budget"></TabPane>
          <TabPane tab="战规版" key="strategy"></TabPane>
          <TabPane tab="投资版" key="investment"></TabPane>
        </Tabs>
        {/* 内容-搜索-创建-编辑。。。。 */}

        <Row type="flex" justify="space-between" align="middle">
          {/* 版本信息 */}
          <Col>
            {versions.length && currentState.length ? (
              <Row type="flex" align="middle">
                <Col>
                  <Select
                    dropdownMatchSelectWidth={false}
                    onChange={value => {
                      router.replace(
                        `/OperatingPlan/ContractPlan/${params.level1}/${params.level2}/${params.project}/${params.stage}/${params.category}/${value}`,
                      );
                    }}
                    size="small"
                    className="version-select"
                    value={currentState[0].versionId}
                  >
                    {versions.map(val => (
                      <Option key={val.versionId} value={val.versionId}>
                        {setSignPlanVersionName(val)}
                      </Option>
                    ))}
                  </Select>
                  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  <Text className="version-status" strong>
                    <i
                      className="dots"
                      style={{
                        background: handlerApprovalStatusColor(versionState),
                      }}
                    />
                    {currentState[0].versionState}&nbsp;&nbsp;
                  </Text>
                  {/* 版本信息 */}
                  <MyBasicInfo data={this.setBasicInfoData(_.head(currentState))} />
                </Col>
                &nbsp;&nbsp;
                {versions.length && currentState.length && currentYear !== '' ? (
                  <>
                    显示：
                    <Select
                      // mode="multiple"
                      size="small"
                      style={{ width: 100 }}
                      placeholder="请选择"
                      value={currentYear}
                      onChange={e => this.changeCurrentYear(e)}
                    >
                      {overAllYears &&
                        overAllYears.length > 0 &&
                        overAllYears.map(data => (
                          <Option key={data}>
                            {data}
                            {new Date().getFullYear().toString() === data.toString()
                              ? '(今年)'
                              : ''}
                          </Option>
                        ))}
                    </Select>
                    &nbsp;&nbsp;
                    <TreeSelect
                      size="small"
                      style={{ width: 230 }}
                      value={currentMonths}
                      mode="multiple"
                      onChange={this.changeCurrentMonths}
                      treeCheckable
                      maxTagCount={2}
                      treeData={months}
                    ></TreeSelect>
                  </>
                ) : null}
              </Row>
            ) : null}
          </Col>
          <Col>
            <Btns
              rowAttribute={{
                gutter: [5, 0],
                type: 'flex',
                justify: 'space-between',
                align: 'middle',
              }}
              BtnsList={BtnsList}
            />
          </Col>
        </Row>
      </>
    );
  }
}
